package com.ruoyi.web.controller.user;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.user.domain.UserLevel;
import com.ruoyi.user.service.UserLevelService;
import com.ruoyi.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 会员Controller
 *
 * @author ruoyi
 * @date 2024-01-04
 */
@Api(tags = "会员管理")
@RestController
@RequestMapping("/user/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private UserLevelService userLevelService;

    /**
     * 查询会员列表
     */
    @ApiOperation("查询会员列表")
    @PreAuthorize("@ss.hasPermi('user:user:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody User user) {
        startPage();
        List<User> list = userService.selectUserList(user);

        if (CollectionUtils.isNotEmpty(list)) {
            // 组装邀请人
            Map<Long, User> recMap = new HashMap<>();
            List<Long> recIds = list.stream().map(User::getRecId).filter(Objects::nonNull).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(recIds)) {
                List<User> recList = userService.selectUserListByRecIds(recIds);
                recList.forEach(rec -> recMap.put(rec.getUserId(), rec));
            }

            // 组装等级名称
            Map<Integer, String> levelMap = new HashMap<>();
            List<Integer> levelValues = list.stream().map(User::getLevelValue).filter(Objects::nonNull).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(levelValues)){
                List<UserLevel>  levelList = userLevelService.selectUserLevelListByLevelValues(levelValues);
                levelList.forEach(level -> levelMap.put(level.getLevelValue(), level.getLevelName()));
            }

            // 查询状态字典
            List<SysDictData> dictDataList = sysDictDataService.selectDictDataList(new SysDictData("sys_common_status", "0"));
            Map<String,  String> dictDataMap = dictDataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            list.forEach(u -> {
                User rec = recMap.get(u.getRecId());
                if (rec != null) {
                    u.setRecNo(rec.getMemberNo());
                } else {
                    u.setRecNo("/");
                }
                u.setStatusStr(dictDataMap.get(u.getStatus()));
                u.setLevelName(levelMap.get(u.getLevelValue()));
            });
        }

        return getDataTable(list);
    }

    /**
     * 导出会员列表
     */
    @ApiOperation("导出会员列表")
    @PreAuthorize("@ss.hasPermi('user:user:export')")
    @Log(title = "会员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user) {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<>(User.class);
        util.exportExcel(response, list, "会员数据");
    }

    /**
     * 获取会员详细信息
     */
    @ApiOperation("获取会员详细信息")
    @PreAuthorize("@ss.hasPermi('user:user:query')")
    @PostMapping(value = "getInfo/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return success(userService.selectUserById(userId));
    }

    /**
     * 保存会员
     */
    @ApiOperation("保存会员")
    @PreAuthorize("@ss.hasPermi('user:user:save')")
    @Log(title = "会员", businessType = BusinessType.SAVE)
    @PostMapping("save")
    public AjaxResult save(@RequestBody User user) {
        if (user.getUserId() == null) {
            return toAjax(userService.insertUser(user));
        } else {
            return toAjax(userService.updateUser(user));
        }
    }

    /**
     * 删除会员
     */
    @PreAuthorize("@ss.hasPermi('user:user:remove')")
    @Log(title = "会员", businessType = BusinessType.DELETE)
    @PostMapping("remove/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }
}
